package com.namo.ccharticle.service.impl;

import com.google.gson.GsonBuilder;
import com.namo.ccharticle.dao.TypeMapper;
import com.namo.ccharticle.entity.Type;
import com.namo.ccharticle.service.TypeService;
import com.namo.cchcommon.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author WangXin
 * @date 2021/5/19 12:56
 */
@Service
@Slf4j
public class TypeServiceImpl implements TypeService {
    @Autowired
    TypeMapper typeMapper;

    @Override
    public List<Type> getTypeList() {


        try {
            List<Type> types = typeMapper.selectAll();
            log.info("查询到分类信息列表");
            return types;
        } catch (Exception e) {
            log.error("查询错误==>"+e.getMessage());
            throw new ApiException(500L,"查询失败");
        }
    }
    @Override
    public Type  addType(String name,Integer status){
        Type type = typeMapper.selectByName(name);
        if (type != null){
            throw new ApiException(500L,"已经存在分类:"+name);
        }
        Type newType = new Type();
        newType.setId(UUID.randomUUID().toString());
        newType.setCreateTime(new Date());
        newType.setName(name);
        newType.setStatus(status);

        try {
            int insert = typeMapper.insert(newType);
            if (insert == 1){
                return newType;
            }else {
                log.error("新建分类插入失败=>插入影响条数："+insert);
                throw new ApiException(500L,"新建分类插入失败");
            }
        } catch (Exception e) {
            log.error("新建分类插入失败=>"+e.getMessage());
            throw new ApiException(500L,"新建分类插入失败");
        }
    }

    @Override
    public Boolean delType(String id) {
        try {
            int delete = typeMapper.deleteByPrimaryKey(id);
            if (delete==0){
                log.error("删除失败=>没有这个数据");
                throw new ApiException(500L,"删除失败");
            }
            return true;
        } catch (Exception e) {
            log.error("删除失败=>"+e.getMessage());
            throw new ApiException(500L,e.getMessage());
        }
    }

    @Override
    public Boolean updateType(Type type) {
        Type typeTemp = typeMapper.selectByName(type.getName());
        try {
            if (typeTemp != null && typeTemp.getId().equals(type.getId())==false){
                throw new ApiException(500L,"已经存在分类:"+type.getName());
            }
            int selective = typeMapper.updateByPrimaryKeySelective(type);
            if (selective==0){
                log.error("更新失败=>没有这个数据");
                throw new ApiException(500L,"更新失败");
            }
            return true;
        } catch (Exception e) {
            log.error("更新失败=>"+e.getMessage());
            throw new ApiException(500L,e.getMessage());
        }
    }
}
